﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.PermissionManagement.IPermissionManagement;
using SqlSugar;
using SportsPlatform.Base;
using Abp.ObjectMapping;
using SportsPlatform.Consts;
using SportsPlatform.Query.PermissionManagement.RoleInfo;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Query.PermissionManagement.BaseQuery;
using SportsPlatform.Dto.PermissionManagement.RoleInfo;
using Abp.Application.Services;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;

namespace SportsPlatform.PermissionManagement.PermissionManagement
{
    /// <summary>
    /// 角色表
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class RoleInfoService : SportsPlatformAppServiceBase, IRoleInfoService
    {
        private readonly IRepository<UserInfo, Guid> _userinfoRepository;

        private readonly IRepository<RoleInfo, Guid> _roleinfoRepository;

        private readonly IRepository<CompanyInfo, Guid> _companyinfoRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="userinfoRepository"></param>
        /// <param name="roleinfoRepository"></param>
        public RoleInfoService(IRepository<UserInfo, Guid> userinfoRepository, IRepository<RoleInfo, Guid> roleinfoRepository,
            IRepository<CompanyInfo, Guid> companyinfoRepository, IHttpContextAccessor context) : base(context)
        {
            _userinfoRepository = userinfoRepository;
            _roleinfoRepository = roleinfoRepository;
            _companyinfoRepository = companyinfoRepository;
        }
        /// <summary>
        /// 新增信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<BaseResultDto> AddRoleInfo(AddRoleInfoQuery query)
        {
            BaseResultDto basePage = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                RoleInfo roleInfo = ObjectMapper.Map<RoleInfo>(query);
                roleInfo.CreateUserId = token.Id;
                roleInfo.CreateTime = DateTime.Now;
                if (query.CompanyId != null && query.CompanyId != Guid.Empty)
                {
                    roleInfo.CompanyId = query.CompanyId;
                }
                else
                {
                    roleInfo.CompanyId = token.CompanyId;
                }
                await _roleinfoRepository.InsertAsync(roleInfo);
                basePage.IsSuccess = true;
                basePage.Code = HttpResultCode.Success;
                basePage.Message = "新增成功！";
            }
            catch (Exception e)
            {
                basePage.IsSuccess = false;
                basePage.Code = HttpResultCode.Error;
                basePage.Message = e.Message.ToString();
            }
            return basePage;
        }

        /// <summary>
        /// 根据Id删除信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<BaseResultDto> DeleteRoleInfo(DeleteOrGetModelQuery query)
        {
            BaseResultDto basePage = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                var roleinfo = _roleinfoRepository.FirstOrDefault(info => info.Id == query.Id);
                if (roleinfo != null)
                {
                    roleinfo.DeleteUserId = token.Id;
                    roleinfo.IsDeleted = true;
                    roleinfo.DeleteTime = DateTime.Now;
                    await _roleinfoRepository.UpdateAsync(roleinfo);
                    basePage.IsSuccess = true;
                    basePage.Code = HttpResultCode.Success;
                    basePage.Message = "删除成功！";
                }
                else
                {
                    basePage.IsSuccess = false;
                    basePage.Code = HttpResultCode.Fail;
                    basePage.Message = "删除失败！未查到有效的数据！ ";
                }
            }
            catch (Exception e)
            {
                basePage.IsSuccess = false;
                basePage.Code = HttpResultCode.Error;
                basePage.Message = e.Message.ToString();
            }
            return basePage;
        }
        /// <summary>
        /// 根据Id查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetRoleInfoDto>> GetRoleInfo(DeleteOrGetModelQuery query)
        {
            ResultDto<GetRoleInfoDto> resultDto = new ResultDto<GetRoleInfoDto>();
            try
            {
                var roleinfo = await _roleinfoRepository.FirstOrDefaultAsync(info => info.Id == query.Id);
                if (roleinfo != null)
                {
                    if (roleinfo.IsDeleted == true)
                    {
                        resultDto.IsSuccess = false;
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.Message = "查询的数据已删除！";
                    }
                    else
                    {
                        resultDto.IsSuccess = true;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.Message = "查询成功！";
                        var roleinfodto = ObjectMapper.Map<GetRoleInfoDto>(roleinfo);
                        roleinfodto.CompanyName = roleinfodto.CompanyId != null ? _companyinfoRepository.FirstOrDefault(info => info.Id == roleinfodto.CompanyId).CompanyName : "";
                        roleinfodto.CreateUserName = roleinfodto.CreateUserId != Guid.Empty ? _userinfoRepository.FirstOrDefault(info => info.Id == roleinfodto.CreateUserId).UserName : "";
                        resultDto.Data = roleinfodto;
                    }
                }
                else
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }
        /// <summary>
        /// 分页获取角色信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetRoleInfoPageDto>> GetRoleInfoPage(GetRoleInfoPageQuery query)
        {
            PagePagingDto<GetRoleInfoPageDto> pagePagingDto = new PagePagingDto<GetRoleInfoPageDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);
                var roleinfolist = (await _roleinfoRepository.GetAllListAsync(info => info.IsDeleted == false))
                    .WhereIF(!string.IsNullOrEmpty(query.RoleName), info => info.RoleName.Contains(query.RoleName))
                    .WhereIF(query.CompanyId != null, info => info.CompanyId == query.CompanyId)
                    .WhereIF(query.CompanyId == null && token.CompanyId != null, info => info.CompanyId == token.CompanyId)
                    .OrderByDescending(info => info.CreateTime)
                    .ToList();
                var roleinfopage = roleinfolist.Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize).ToList();
                if (roleinfopage != null && roleinfopage.Count > 0)
                {
                    var userlist = await _userinfoRepository.GetAllListAsync();
                    var companylist = await _companyinfoRepository.GetAllListAsync();
                    var list = new List<GetRoleInfoPageDto>();
                    foreach (var item in roleinfopage)
                    {
                        var dto = new GetRoleInfoPageDto();
                        dto.States = item.States;
                        dto.RoleDescribe = item.RoleDescribe;
                        dto.CreateUserName = item.CreateUserId != Guid.Empty ? (userlist.Where(info => info.Id == item.CreateUserId).FirstOrDefault().UserName) : "";
                        dto.CompanyId = item.CompanyId;
                        dto.CompanyName = item.CompanyId != null ? (companylist.Where(info => info.Id == item.CompanyId).FirstOrDefault().CompanyName) : "";
                        dto.Id = item.Id;
                        dto.RoleName = item.RoleName;
                        dto.CreateTime = item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                        list.Add(dto);
                    }

                    pagePagingDto.Data = list;
                    pagePagingDto.IsSuccess = true;
                    pagePagingDto.Code = HttpResultCode.Success;
                    pagePagingDto.Message = "查询成功！";
                    pagePagingDto.TotalCount = roleinfolist.Count;
                }
                else
                {
                    pagePagingDto.TotalCount = 0;
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.SqlError;
                    pagePagingDto.Message = "未查询到相关角色信息！";
                }
            }
            catch (Exception e)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = e.Message.ToString();
            }
            return pagePagingDto;
        }

        /// <summary>
        /// 获取角色名称集合
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetRoleNameListDto>> GetRoleNameList(GetRoleNameListQuery query)
        {
            ResultListDto<GetRoleNameListDto> resultListDto = new ResultListDto<GetRoleNameListDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);
                //如果没有传入公司id？根据查询的用户公司id获取：（如果是平台的人？返回平台角色+传入公司Id对应的角色：返回传入公司Id对应的角色）
                var roleinfolist = await _roleinfoRepository.GetAllListAsync(info => ((query.CompanyId == null || query.CompanyId == Guid.Empty) ? info.CompanyId == token.CompanyId : (token.CompanyId == null ? (info.CompanyId == null || info.CompanyId == Guid.Empty || info.CompanyId == query.CompanyId) : info.CompanyId == query.CompanyId)) && info.IsDeleted == false && info.States == true);
                if (roleinfolist != null && roleinfolist.Count > 0)
                {
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Count = roleinfolist.Count;
                    List<GetRoleNameListDto> getRoleNameListDtos = new List<GetRoleNameListDto>();
                    var companylist = await _companyinfoRepository.GetAllListAsync();
                    roleinfolist.ForEach(item =>
                    {
                        GetRoleNameListDto getRoleNameListDto = new GetRoleNameListDto();
                        getRoleNameListDto.Id = item.Id;
                        getRoleNameListDto.RoleName = item.RoleName;
                        getRoleNameListDto.CompanyName = item.CompanyId != null ? companylist.Where(info => info.Id == item.CompanyId).FirstOrDefault().CompanyName : "平台端";
                        getRoleNameListDtos.Add(getRoleNameListDto);
                    });
                    resultListDto.Data = getRoleNameListDtos;
                }
                else
                {
                    resultListDto.IsSuccess = false;
                    resultListDto.Code = HttpResultCode.Error;
                    resultListDto.Message = "未查询到角色！";
                }

            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }
        /// <summary>
        /// 批量/单个更改用户状态
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> RoleInfoBatchChangeOfStatus(RoleInfoBatchChangeOfStatusQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                Guid userid = token.Id;
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.SqlError;
                int failnumber = 0;//更新失败数量
                string failid = "";//更新失败Id
                if (query.List != null && query.List.Count > 0)
                {
                    List<Guid> idlist = new List<Guid>();
                    query.List.ForEach(item => { idlist.Add(item.Id); });
                    for (int i = 0; i < idlist.Count; i++)
                    {
                        var roleinfo = await _roleinfoRepository.FirstOrDefaultAsync(info => info.Id == idlist[i]);
                        if (roleinfo != null)
                        {
                            roleinfo.States = query.States;
                            roleinfo.UpdateTime = DateTime.Now;
                            roleinfo.UpdateUserId = userid;
                            await _roleinfoRepository.UpdateAsync(roleinfo);
                            baseResultDto.IsSuccess = true;
                            baseResultDto.Code = HttpResultCode.Success;
                            baseResultDto.Message = "更改成功！";
                        }
                        else
                        {
                            failnumber++;
                            failid += string.IsNullOrEmpty(failid) ? idlist[i].ToString() : "," + idlist[i].ToString();
                            baseResultDto.Message = string.Format("一共更新{0}条，失败{1}条,失败id:{2}!", idlist.Count.ToString(), failid.ToString(), failid);
                        }
                    }
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "IDList不能为空！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }
        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateRoleInfo(UpdateRoleInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                var roleinfo = _roleinfoRepository.FirstOrDefault(info => info.Id == query.Id);
                if (roleinfo != null)
                {
                    if (!string.IsNullOrEmpty(query.RoleName))
                    {
                        roleinfo.RoleName = query.RoleName;
                    }
                    if (!string.IsNullOrEmpty(query.RoleDescribe))
                    {
                        roleinfo.RoleDescribe = query.RoleDescribe;
                    }
                    if (query.CompanyId != null && query.CompanyId != Guid.Empty)
                    {
                        roleinfo.CompanyId = query.CompanyId;
                    }
                    else if (token.CompanyId == null)
                    {
                        roleinfo.CompanyId = null;
                    }
                    if (query.States != null)
                    {
                        roleinfo.States = (bool)query.States;
                    }
                    roleinfo.UpdateUserId = token.Id;
                    roleinfo.UpdateTime = DateTime.Now;
                    await _roleinfoRepository.UpdateAsync(roleinfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更改成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "未查询到Id数据！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }
    }
}
